<template>
  <div
    class="sticky z-10 top-0 bg-white pb-4 pt-4 w-full md:mx-4 md:w-[calc(100%-2rem)] md:bg-[var(--custom-bg)]"
    style="--custom-bg: #f9f9f9"
    @click="handleClickOverlay">
    <div class="h-12 flex items-center justify-between hidden md:flex">
      <img :src="logoSrc" alt="" class="w-40 h-auto cursor-pointer" />
      <div class="flex items-center">
        <div
          v-for="item in tabbarItems"
          :key="item.name"
          class="h-12 flex items-center justify-center px-4 cursor-pointer hover:bg-gray-100 transition-colors duration-200"
          @click="handleTabbarClick(item)">
          <img :src="item.icon" :class="['w-25 h-auto']" />
          <!-- <span class="text-md ml-1">{{ isZh ? item.name : item.nameEn }}</span> -->
        </div>
      </div>
    </div>

    <!-- tabs -->
    <div ref="myElement">
      <van-tabs v-model="active" @change="handleChange" key="1">
        <van-tab v-for="(item, index) in tabs" :key="item.key">
          <div slot="title" class="flex flex-col items-center mb-2 cursor-pointer hover:bg-gray-200 px-4">
            <div
              class="icon-container overflow-hidden flex justify-center items-center"
              :style="{
                height: containerHeight + 'px',
                transition: 'height 0.1s ease-out, margin-bottom 0.1s ease-out',
              }">
              <img
                :src="item.icon"
                alt=""
                class="w-8 h-8 z-999"
                :style="{
                  transform: `scale(${iconScale})`,
                  opacity: iconOpacity,
                  transition: 'transform 0.1s ease-out, opacity 0.1s ease-out',
                  transformOrigin: 'center',
                  willChange: 'transform, opacity',
                }" />
            </div>
            <span
              :style="{
                transition: 'margin-top 0.1s ease-out',
              }">
              {{ item.title }}
            </span>
          </div>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 搜索框 -->
    <div class="h-12 rounded flex items-center justify-center relative overflow-visible">
      <div
        class="w-4/5 h-12 rounded-full border border-gray-200 flex items-center justify-center pl-4 bg-white cursor-pointer"
        @click.stop="handleSearch">
        <img :src="searchSrc" class="w-6 h-6" alt="" />
        <input
          v-model="searchText"
          @keyup.enter="getPlaceList"
          type="text"
          class="w-full h-full pl-4 cursor-pointer"
          :placeholder="activeTab === 2 ? $t('query.searchText') : $t('home.searchText')" />
      </div>
    </div>

    <van-popup v-model="showPlaceList" position="top" :class="['flex items-start justify-center home-container home-popup', popupClass]" :style="popupVars">
      <div class="w-4/5 h-140 bg-white rounded-2xl overflow-y-auto border border-gray-200 p-4">
        <!-- 最近搜索 -->
        <div class="mb-6" v-if="recentSearches.length > 0">
          <h3 class="text-sm font-medium text-gray-600 mb-3">最近搜索</h3>
          <div class="space-y-2">
            <div
              v-for="search in recentSearches"
              :key="search.code"
              class="flex items-center cursor-pointer hover:bg-gray-50 p-2 rounded"
              @click="handleRecentSearch(search)">
              <img :src="imageBaseUrl + item" v-for="item in search.placeIconList" :key="item" :alt="search.place" class="w-5 h-4 mr-2" />
              <span class="text-sm">{{ isZh ? search.place : search.placeEn }}</span>
            </div>
          </div>
        </div>

        <!-- 热门推荐 -->
        <div>
          <h3 class="text-sm font-medium text-gray-600 mb-3">热门推荐</h3>
          <div class="space-y-3">
            <div
              v-for="destination in popularDestinations"
              :key="destination.code"
              class="flex items-center cursor-pointer hover:bg-gray-50 p-2 rounded"
              @click="handleDestinationClick(destination)">
              <img
                :src="imageBaseUrl + item"
                v-for="item in destination.placeIconList"
                :key="item"
                :alt="destination.place"
                class="w-5 h-4 mr-3" />
              <span class="text-sm">{{ isZh ? destination.place : destination.placeEn }}</span>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
    <!-- 搜索弹出层 -->
    <van-popup v-model="show" position="center" class="h-[100%] pt-4 yoyo-container w-full">
      <van-icon name="cross" size="26" class="absolute top-4 right-4 z-10" @click="show = false" />
      <van-tabs v-model="searchActive" @change="handleChangeSearch" class="flex-1 w-[60%] mx-auto h-16" key="2">
        <van-tab v-for="(item, index) in searchTabs" :key="item.key">
          <div slot="title" class="flex flex-col items-center mb-2 cursor-pointer hover:bg-gray-100 px-4">
            <img :src="item.icon" class="w-8 h-8" alt="" />
            <span class="mt-1">{{ item.title }}</span>
          </div>
        </van-tab>
      </van-tabs>

      <div class="mt-4 h-12 bg-white rounded flex items-center justify-center relative overflow-visible">
        <div class="w-4/5 min-h-12 rounded-full border border-gray-200 flex items-center justify-center pl-4">
          <img :src="searchSrc" class="w-6 h-6" alt="" />
          <input
            v-model="searchText"
            type="text"
            class="w-full h-full pl-4"
            :placeholder="$t('home.searchText')"
            @keyup.enter="getPlaceList" />
        </div>
      </div>
      <div
        class="mx-4 w-[calc(100%-2rem)] mt-4 rounded-2xl border border-1 border-gray-200 box-border p-4 h-[calc(100%-14rem)] overflow-y-auto">
        <!-- 最近搜索 -->
        <div class="mb-6" v-if="recentSearches.length > 0">
          <h3 class="text-sm font-medium text-gray-600 mb-3">最近搜索</h3>
          <div class="space-y-2">
            <div
              v-for="search in recentSearches"
              :key="search.code"
              class="flex items-center cursor-pointer hover:bg-gray-50 p-2 rounded"
              @click="handleRecentSearch(search)">
              <img :src="imageBaseUrl + search.placeIcon" :alt="search.place" class="w-5 h-4 mr-2" />
              <span class="text-sm">{{ isZh ? search.place : search.placeEn }}</span>
            </div>
          </div>
        </div>

        <!-- 热门推荐 -->
        <div>
          <h3 class="text-sm font-medium text-gray-600 mb-3">热门推荐</h3>
          <div class="space-y-3">
            <div
              v-for="destination in popularDestinations"
              :key="destination.code"
              class="flex items-center cursor-pointer hover:bg-gray-50 p-2 rounded"
              @click="handleDestinationClick(destination)">
              <img :src="imageBaseUrl + destination.placeIcon" :alt="destination.place" class="w-5 h-4 mr-3" />
              <span class="text-sm">{{ isZh ? destination.place : destination.placeEn }}</span>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Tab, Tabs, Popup } from "vant"
import { getPlaceList } from "@/apis/shop"
import { mapGetters } from "vuex"
export default {
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Popup.name]: Popup,
  },
  props: {
    activeTab: {
      type: Number,
      default: 0,
    },
    scrollProgress: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      value: "",
      active: 0,
      searchActive: 0,
      searchSrc: require("@/assets/images/search-icon.png"),
      show: false,
      showPlaceList: false,
      popularDestinations: [],
      recentSearches: [],
      searchText: "", // 搜索文本
      showTabIcon: false,
      logoSrc: require("@/assets/images/logo.png"),
      tabHeight: 0,
      dynamicHeight: 0,
    }
  },
  computed: {
    ...mapGetters({
      isZh: "lang/isZh",
    }),
    imageBaseUrl() {
      return process.env.VUE_APP_IMAGE_URL
    },
    popupClass() {
      const baseClass = "top-[calc(5rem+var(--popup-tab-height,0px))] sm:top-[calc(5rem+var(--popup-tab-height,0px))]"
      const desktopClass = "md:top-[calc(8rem+var(--popup-tab-height,0px))] "
      return `${baseClass} ${desktopClass}`
    },
    popupVars() {
      return {
        "--popup-tab-height": `${this.tabHeight}px`,
      }
    },
    tabbarItems() {
      return this.isZh
        ? [
            {
              name: "购物车",
              nameEn: "Cart",
              icon: require("@/assets/images/PC/cart.png"),
              to: { name: "cart", query: { showTabbar: true } },
            },
            {
              name: "YOYO币介绍",
              nameEn: "Introduction to YOYO Coin",
              icon: require("@/assets/images/PC/yoyo.png"),
              to: { name: "yoyoCoinIntroduce" },
            },
            {
              name: "个人中心",
              nameEn: "Personal center",
              icon: require("@/assets/images/PC/my.png"),
              to: { name: "mine" },
            },
          ]
        : [
            {
              name: "Cart",
              nameEn: "Cart",
              icon: require("@/assets/images/PC/cart-en.png"),
              to: { name: "cart", query: { showTabbar: true } },
              w: 8,
            },
            {
              name: "Introduction to YOYO Coin",
              nameEn: "Introduction to YOYO Coin",
              icon: require("@/assets/images/PC/yoyo-en.png"),
              to: { name: "yoyoCoinIntroduce" },
              w: 10,
            },
            {
              name: "Personal center",
              nameEn: "Personal center",
              icon: require("@/assets/images/PC/my-en.png"),
              to: { name: "mine" },
              w: 10,
            },
          ]
    },
    tabs() {
      return [
        { title: this.$t("home.esim"), icon: require("@/assets/images/esim.png"), key: "esim" },
        { title: this.$t("home.sim"), icon: require("@/assets/images/sim.png"), key: "sim" },
        { title: this.$t("home.search"), icon: require("@/assets/images/search.png"), key: "search" },
      ]
    },

    searchTabs() {
      return [
        { title: this.$t("home.esim"), icon: require("@/assets/images/esim.png"), key: "esim2" },
        { title: this.$t("home.sim"), icon: require("@/assets/images/sim.png"), key: "sim2" },
      ]
    },
    heightStyle() {
      return {
        top: `calc(80px + ${this.tabHeight}px)`,
      }
    },

    // 根据滚动进度计算动画值
    iconScale() {
      // 从 1 缩放到 0，根据滚动进度
      return Math.max(0, 1 - this.scrollProgress)
    },

    iconOpacity() {
      // 从 1 淡化到 0，根据滚动进度
      return Math.max(0, 1 - this.scrollProgress)
    },

    containerHeight() {
      // 从 40px 缩减到 0px，根据滚动进度
      return Math.max(0, 40 * (1 - this.scrollProgress))
    },

    containerMargin() {
      // 从 8px 缩减到 0px，根据滚动进度
      return Math.max(0, 8 * (1 - this.scrollProgress))
    },

    textMargin() {
      // 文字的上边距，从 8px 缩减到 0px
      return Math.max(0, 8 * (1 - this.scrollProgress))
    },
  },
  watch: {
    scrollProgress(newVal, oldVal) {
      // 监控scrollProgress变化
      const diff = Math.abs(newVal - oldVal)
      if (diff > 0) {
        // console.log('🔄 [HomeHeader接收] scrollProgress变化:', oldVal.toFixed(3), '→', newVal.toFixed(3), '| 差值:', diff.toFixed(3))
      }
    },
  },
  methods: {
    async getPlaceList() {
      try {
        const type = this.active === 1 ? "sim" : "esim"
        const res = await getPlaceList({ type, keyword: this.searchText })
        console.log("res :>> ", res)
        this.popularDestinations = res.data || []
        this.popularDestinations = this.popularDestinations.concat(this.popularDestinations)
        this.popularDestinations = this.popularDestinations.concat(this.popularDestinations)
        this.popularDestinations = this.popularDestinations.concat(this.popularDestinations)
      } catch (error) {
        console.log("object :>> ", error)
      }
    },
    handleChange(index) {
      this.active = index
      this.$emit("change-tabs", index)
    },
    handleChangeSearch(index) {
      this.searchActive = index
      this.searchText = ""
      this.recentSearches = []
      this.loadRecentSearches()
      this.getPlaceList()
    },
    // 处理目的地点击，保存到最近搜索
    handleDestinationClick(destination) {
      this.saveToRecentSearches(destination)
      this.show = false
      this.$router.push({ path: "/products/detail", query: { id: destination.id, type: this.searchActive === 1 ? "sim" : "esim" } })
    },
    // 处理最近搜索点击
    handleRecentSearch(search) {
      this.saveToRecentSearches(search)
      this.show = false
      this.$router.push({ path: "/products/detail", query: { id: search.id, type: this.searchActive === 1 ? "sim" : "esim" } })
      // this.$emit("click-item", search)
    },
    // 保存到最近搜索（最多3条）
    saveToRecentSearches(destination) {
      // 移除已存在的相同项目
      this.recentSearches = this.recentSearches.filter((item) => item.code !== destination.code)
      // 添加到开头
      this.recentSearches.unshift(destination)
      // 保持最多3条记录
      if (this.recentSearches.length > 3) {
        this.recentSearches = this.recentSearches.slice(0, 3)
      }
      // 保存到localStorage
      localStorage.setItem("yoyotravel_recentSearches" + this.searchActive, JSON.stringify(this.recentSearches))
    },
    // 从localStorage加载最近搜索
    loadRecentSearches() {
      const saved = localStorage.getItem("yoyotravel_recentSearches" + this.searchActive)
      if (saved) {
        try {
          this.recentSearches = JSON.parse(saved)
          console.log("this.recentSearches :>> ", this.recentSearches)
        } catch (e) {
          console.error("Failed to parse recent searches:", e)
          this.recentSearches = []
        }
      }
    },
    handleSearch() {
      if (this.active !== 2) {
        if (!this.showPlaceList) {
          this.getPlaceList()
        }
        this.tabHeight = this.$refs.myElement.offsetHeight
        // this.show = true
        this.showPlaceList = true
        this.loadRecentSearches()
      } else {
        this.$emit("search")
      }
    },
    handleTabbarClick(item) {
      this.$router.push(item.to)
    },
    handleClickOverlay() {
      this.showPlaceList = false
      this.searchText = ''
    },
  },
  created() {
    this.loadRecentSearches()
    this.getPlaceList()
  },
}
</script>

<style scoped>
/deep/.van-tabs--line .van-tabs__wrap {
  height: auto;
  width: 80%;
  margin-inline: auto;
}
/deep/.van-tabs__nav {
  background-color: transparent !important;
}
.icon-container {
  transition: height 0.05s ease-out, margin-bottom 0.05s ease-out;
}

.icon-container img {
  transition: transform 0.05s ease-out, opacity 0.05s ease-out;
  transform-origin: center;
  will-change: transform, opacity;
}
/deep/.van-popup {
  background: transparent;
}
/deep/.home-popup {
  left: 0;
  right: 0;
  /* width: 100%; */
  margin-inline: auto;
  /* padding-inline: 1rem; */
}
/deep/.van-overlay {
  display: none;
}
</style>
